package com.sport.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.sport.model.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;

// 全局异常处理器
@Slf4j
@RestControllerAdvice
public class GlobalException {

    // 处理 Sa-Token 的未登录异常
    @ExceptionHandler(NotLoginException.class)
    public Result<String> handleException(NotLoginException e, HttpServletRequest request) {
        //如果没有传递token，就应该返回未传递登录凭证
        String tokenName = request.getHeader(StpUtil.getTokenName());
        if(StrUtil.isBlank(tokenName)){
            return Result.error(401, "请先登录！", request.getRequestURI());
        }
        log.error("Sa-Token鉴赏异常  url:{}", request.getRequestURI(), e);
        return Result.error(401, e.getMessage(), request.getRequestURI());
    }

    @ExceptionHandler(NotPermissionException.class)
    public Result<String> handleException(NotPermissionException e, HttpServletRequest request) {
        log.error("Sa-Token鉴赏异常  url:{}", request.getRequestURI(), e);
        return Result.error(403, e.getMessage(), request.getRequestURI());
    }

    //捕获角色异常
    @ExceptionHandler(NotRoleException.class)
    public Result<String> handleException(NotRoleException e, HttpServletRequest request) {
        log.error("Sa-Token鉴赏异常  url:{}", request.getRequestURI(), e);
        return Result.error(403, e.getMessage(), request.getRequestURI());
    }

    //捕获SQL异常
    @ExceptionHandler(SQLException.class)
    public Result<String> handleException(SQLException e, HttpServletRequest request) {
        log.error("SQL鉴赏异常  url:{}", request.getRequestURI(), e);
        return Result.error(500,"SQL异常", e.getMessage());
    }
}
